package io.xxx.omni.oss.sdk

import com.google.gson.JsonObject
import io.xxx.omni.oss.common.toJsonObject
import io.xxx.omni.oss.common.zoneOffset
import io.xxx.omni.oss.domain.Store
import org.apache.commons.codec.digest.DigestUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.HttpEntity
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpMethod
import org.springframework.stereotype.Component
import org.springframework.web.client.RestTemplate
import java.time.LocalDateTime
import java.util.*

@Component
class PddClient {

    @Autowired
    private lateinit var restTemplate: RestTemplate

    private val httpUrl = "https://gw-api.pinduoduo.com/api/router"

    fun execute(store: Store, type: String, request: Map<String, Any>): JsonObject {
        val authorization = store.authorization
        val signMap = TreeMap(request)
        signMap["type"] = type
        signMap["client_id"] = authorization["client_id"]
        signMap["timestamp"] = LocalDateTime.now().toEpochSecond(zoneOffset)
        signMap["data_type"] = "JSON"
        signMap["access_token"] = authorization["access_token"]
        val builder = StringBuilder()
            .append(authorization["app_secret"])
            .append(signMap.entries.joinToString("") { it.key + it.value })
            .append(authorization["app_secret"])
        signMap["sign"] = DigestUtils.md5Hex(builder.toString()).uppercase()

        val headers = HttpHeaders()
        headers["Content-Type"] = "application/json"
        val entity = HttpEntity(signMap, headers)
        return restTemplate.exchange(httpUrl, HttpMethod.POST, entity, String::class.java).body!!.toJsonObject()
    }
}